<template>
    <div class="main coupon-edit">
        <section>
            <el-form  size="medium" ref="form" label-width="150px" :rules="commonRules" :model="busMaterial">
                <div class="block-header"><div>素材内容</div></div>
                <div class="block-content">
                    <el-form-item label="素材标题:" prop="title" :rules="commonRules.notNullRule">
                      <el-input v-model="busMaterial.title" placeholder="用于后台快速查找素材，不超过30字" maxlength="30"></el-input>
                    </el-form-item>
                    <el-form-item label="封面图片:" prop="resource">
                      <el-upload
                        class="avatar-uploader"
                        accept="image/*"
                        :action="upladUrl"
                        name="file"
                        :show-file-list="false"
                        :before-upload="beforeUpload"
                        :on-success="(res)=>{
                        busMaterial.cover = replaceImgUrl(res.filePath)
                      }">
                      <img v-if="busMaterial.cover" :src="busMaterial.cover" class="avatar">
                      <i v-if="!busMaterial.cover" class="el-icon-plus avatar-uploader-icon"></i>
                      <span v-if="!busMaterial.cover" class="uploadLocal">本地上传</span>
                      </el-upload>
                      <div style="color: red">单张图片控制在5M以内</div>   
                    </el-form-item>
                    <el-form-item label="素材类型:" prop="type" :rules="commonRules.notNullRule">
                        <el-radio-group v-model="busMaterial.type" >
                            <el-radio  :label="1">单图文素材</el-radio>
                            <el-radio  :label="2">多图文素材</el-radio>
                            <el-radio  :label="3">视频素材</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="素材分组/标签:" prop="groupValue" :rules="commonRules.notNullRule">
                        <el-cascader
                        :options="groupList"
                        change-on-select
                        v-model="busMaterial.groupValue"
                        clearable></el-cascader>
                    </el-form-item>
                    <el-form-item label="分享文案:" prop="content" :rules="commonRules.notNullRule">
                        <!-- <tinymce :height="320" v-model="busMaterial.content"></tinymce> -->
                        <el-input  type="textarea" v-model="busMaterial.content" maxlength="800" placeholder="请输入文案，800字以内，支持特殊符号及表情输入"></el-input>
                    </el-form-item>
                    <el-form-item label="素材图片:" prop="resource" :rules="commonRules.notNullRule"  v-if="busMaterial.type===1">
                        <el-upload
                                class="avatar-uploader"
                                accept="image/*"
                                :action="upladUrl"
                                name="file"
                                :show-file-list="false"
                                :before-upload="beforeUpload"
                                :on-success="(res)=>{
                            busMaterial.resource = replaceImgUrl(res.filePath)
                        }">
                        <img v-if="busMaterial.resource" :src="busMaterial.resource" class="avatar">
                        <i v-if="!busMaterial.resource" class="el-icon-plus avatar-uploader-icon"></i>
                        <span v-if="!busMaterial.resource" class="uploadLocal">本地上传</span>
                        </el-upload>
                        <div style="color: red">单张图片控制在5M以内</div>   
                    </el-form-item>
                    <el-form-item label="素材图片:" prop="resourceList" :rules="commonRules.notNullRule" v-if="busMaterial.type===2">
                        <ul class="upload-img-list">
                            <draggable v-model="busMaterial.resourceList" :options="{group:'resourceList'}" @start="drag=true" @end="drag=false">
                                <li class="img-preview" v-for="(imgItem, imgIndex) of busMaterial.resourceList" :key="imgIndex" >
                                    <img :src="imgItem" alt="">
                                    <div class="img-preview-mask">
                                        <div class="mask-btn">
                                            <i title="删除" class="el-icon-delete" @click="()=>{busMaterial.resourceList.splice(imgIndex, 1)}"></i>
                                        </div>
                                    </div>
                                </li>
                            </draggable>
                            <li>
                                <label class="upload-btn">
                                    <input type="file" @change="(event)=>{uploadImg(event, busMaterial.resourceList)}"/>
                                    <i class="el-icon-plus avatar-uploader-icon"></i>
                                    <span class="uploadLocal">本地上传</span>
                                </label>
                            </li>
                        </ul>
                        <div style="color: red">最多添加9张，单张图片控制在5M以内</div>
                    </el-form-item>
                    <el-form-item label="素材视频:" prop="videoResource" :rules="commonRules.notNullRule"  v-if="busMaterial.type===3">
                        <el-upload 
                                class="avatar-uploader"
                                accept="video/mp4,video/quicktime"
                                :action="upladUrl"
                                name="file"
                                :show-file-list="false"
                                :before-upload="beforeUploadVideo"
                                :on-success="(res)=>{
                            busMaterial.videoResource = replaceImgUrl(res.filePath)
                        }">
                            <video v-if="busMaterial.videoResource" autoplay="autoplay" loop="loop"  :src="busMaterial.videoResource">
                                您的浏览器不支持HTML5 Video
                            </video>
                            <i v-if="!busMaterial.videoResource" class="el-icon-plus avatar-uploader-icon"></i>
                            <span v-if="!busMaterial.videoResource" class="uploadLocal">本地上传</span>
                        </el-upload>
                        <div style="color: red">视频控制在50M以内，MP4、MOV格式</div>  
                    </el-form-item>
                    <el-form-item label="视频预览图片:" prop="videoPicUrl" :rules="commonRules.notNullRule" v-if="busMaterial.type===3">
                         <el-upload
                                class="avatar-uploader"
                                accept="image/*"
                                :action="upladUrl"
                                name="file"
                                :show-file-list="false"
                                :before-upload="beforeUpload"
                                :on-success="(res)=>{
                            busMaterial.videoPicUrl = replaceImgUrl(res.filePath)
                        }">
                        <img v-if="busMaterial.videoPicUrl" :src="busMaterial.videoPicUrl" class="avatar">
                        <i v-if="!busMaterial.videoPicUrl" class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                        <div style="color: red">单张图片控制在5M以内</div>
                    </el-form-item>
                    <el-form-item label="">
                        <el-button type="primary" plain  @click="chooseMaterial">
                            从素材库选择
                        </el-button>
                    </el-form-item>     
                    <el-form-item label="分享人数:"  prop="fakeShareNum" :rules="commonRules.numberRule" >
                        <el-input  v-model="busMaterial.fakeShareNum" placeholder="请输入分享人数"></el-input>
                    </el-form-item> 
                    <el-form-item label="素材排序:"  prop="sort" :rules="commonRules.numberRule" >
                        <el-input  v-model="busMaterial.sort" placeholder="数字越大越靠前">
                             <template slot="append">已排序至{{sortLast}}</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="跳转类型:"  prop="linkType" :rules="commonRules.notNullRule" >
                        <el-radio-group v-model="busMaterial.linkType">
                            <el-radio :label="1">无</el-radio>
                            <el-radio :label="2">URL</el-radio>
                            <el-radio :label="3">内页</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="链接图片:"  prop="linkUrl.picUrl" :rules="commonRules.notNullRule" v-if="busMaterial.linkType === 2">
                        <el-upload
                                class="avatar-uploader"
                                accept="image/*"
                                :action="upladUrl"
                                name="file"
                                :show-file-list="false"
                                :before-upload="beforeUpload"
                                :on-success="(res)=>{
                            busMaterial.linkUrl.picUrl = replaceImgUrl(res.filePath)
                        }">
                            <img v-if="busMaterial.linkUrl.picUrl" :src="busMaterial.linkUrl.picUrl" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload> 
                    </el-form-item>
                    <el-form-item label="链接文案:"  prop="linkUrl.content" :rules="commonRules.notNullRule" v-if="busMaterial.linkType === 2">
                        <el-input  v-model="busMaterial.linkUrl.content" placeholder="请输入链接文案"></el-input>
                    </el-form-item>
                    <el-form-item label="链接地址:"  prop="linkUrl.targetValue" :rules="commonRules.notNullRule" v-if="busMaterial.linkType === 2">
                        <el-input  v-model="busMaterial.linkUrl.targetValue" placeholder="请输入链接地址"></el-input>
                    </el-form-item>
                    <el-form-item label="内页类型:"  :rules="commonRules.notNullRule"  prop="goodsOrpackage" v-if="busMaterial.linkType === 3">
                        <el-radio-group v-model="busMaterial.goodsOrpackage">
                            <!-- <el-radio :label="1">url</el-radio> -->
                            <el-radio :label="1">商品</el-radio>
                            <el-radio :label="2">套餐</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="跳转"   :rules="commonRules.notNullRule" prop="goodsOrpackage"  v-if="busMaterial.linkType === 3">
                        <span v-if="busMaterial.goodsOrpackage===1">{{busMaterial.goodsChecked.length>0?busMaterial.goodsChecked[0].content:''}}</span>
                        <span v-else>{{busMaterial.packageChecked.length>0?busMaterial.packageChecked[0].content:''}}</span>
                        <el-button plain type="primary"  @click="chooseGoods">请选择</el-button>
                    </el-form-item>
                </div>
                <el-form-item label="" style="margin-top:20px;">
                    <el-button type="primary" plain size="medium" :loading="btnLoading" @click="save" >保存</el-button>
                    <el-button type="info" size="medium" plain @click="$router.push({ name: 'material' })">返回</el-button>
                </el-form-item> 
            </el-form> 
        </section>
    </div>
</template>
<script>
import { getTagList } from '../../../api/common'
import draggable from 'vuedraggable'
import Tinymce from '@/components/Tinymce'
  export default {
    name: 'materialLibraryEdit',
    components: {
      Tinymce,
      draggable
    },
    mounted(){
        this.busMaterial.id = this.$route.query.id
        if(this.busMaterial.id) {
            this.getConfig()
        }
    },
    created(){
        this.getTagGroup()
        this.getSortLast()
    },
    data(){
        return {	
            busMaterial: {
              cover: '',
                content: '',
                copyNum: 0,
                groupId: '',
                groupValue:[],
                id: 0,
                linkObject: {
                    content: '',
                    marketPrice: 0,
                    picUrl: '',
                    price: 0,
                    targetValue: '',
                    goodsType: 1,
                    packType:'',
                    fromType:1
                },
                goodsOrpackage: 1,
                linkUrl: {content: '', marketPrice: 0, picUrl: '', price: 0, targetValue: '', goodsType: '', packType:'', fromType:1},
                linkType: 1,
                resource: '',
                resourceList: [],
                videoResource:'',
                videoPicUrl:'',
                fakeShareNum:'',
                sort: '',
                tagId: '',
                title: '',
                type: 1,
                goodsChecked: [],
                packageChecked: [],
            },
            groupList:[],
            btnLoading: false,
            sortLast:'',
            showEmoji:false,
            emojiData:[]
        }
    },
    methods: {
        selectEmoji (code) {
            this.showEmoji = false
            this.emojiData.push(code)
            // this.busMaterial.content += code
        },
        getConfig(){
            this.request({
            url: '/bus-material/get?id='+this.busMaterial.id,
            method: 'get',
            }).then((res) => {
                if(res.code===200) {
                    var resource = res.data.resourceObjectList
                    var resourceList = []
                    if(res.data.type === 2){
                        resource.forEach(item=>{
                            resourceList.push(item.resourceUrl)
                        })
                    }
                    this.busMaterial = {
                        ...res.data,
                        resource: res.data.type === 1 ? resource[0].resourceUrl : '',
                        resourceList: res.data.type === 2 ? resourceList  : [],
                        videoResource: res.data.type === 3 ? resource[0].resourceUrl : '',
                        videoPicUrl: res.data.type === 3 ? resource[0].videoPicUrl : '',
                        groupValue: res.data.tagId ? [res.data.groupId, res.data.tagId] :[res.data.groupId],
                        linkUrl: (res.data.linkObject && !res.data.linkObject.goodsType) ? res.data.linkObject : { content: '', marketPrice: 0, picUrl: '', price: 0, targetValue: '', goodsType:'', packType:'', fromType:''},
                        goodsChecked: (res.data.linkObject && res.data.linkObject.goodsType === 1) ? [
                            {content: res.data.linkObject.content,
                            marketPrice: res.data.linkObject.marketPrice,
                            picUrl: res.data.linkObject.picUrl,
                            price: res.data.linkObject.price,
                            goodsId: res.data.linkObject.targetValue,
                            goodsType: res.data.linkObject.goodsType,
                            fromType: res.data.linkObject.fromType,
                            packType: res.data.linkObject.packType,
                            }] : [],
                        packageChecked: (res.data.linkObject && res.data.linkObject.goodsType === 2) ? [{
                            content: res.data.linkObject.content,
                            marketPrice: res.data.linkObject.marketPrice,
                            picUrl: res.data.linkObject.picUrl,
                            price: res.data.linkObject.price,
                            packageId: res.data.linkObject.targetValue,
                            goodsType: res.data.linkObject.goodsType,
                            fromType: res.data.linkObject.fromType,
                            packType: res.data.linkObject.packType
                        }] : [],
                        goodsOrpackage: res.data.linkObject ? res.data.linkObject.goodsType : 1
                    }
                }
            }).catch(err => {
               this.$message.error(err.message)
            });
        },
        chooseMaterial() {
            if(this.busMaterial.type===1){
                this.materialLibrary([], 1, 4).then(val => {
                    this.busMaterial.resource = val[0].resource 
                    if(val[0].content){
                        this.busMaterial.content = val[0].content
                    }
                    console.log(this.busMaterial.content)
                }).catch(err => {
                    // this.busMaterial.resource = ''
                })
            }else if(this.busMaterial.type===2){
                this.materialLibrary([], -1, 4).then(val => {
                    if(this.busMaterial.resourceList.length+val.length > 9){
                        this.$message.error('上传超过9张图片')
                        return false
                    }
                    for(var i=0;i<val.length;i++){
                        this.busMaterial.resourceList.push(val[i].resource)
                        if(val[i].content){
                            this.busMaterial.content += val[i].content
                        }
                    }
                    console.log(this.busMaterial.content)
                }).catch(err => {
                    this.$message.error(err)
                })
            } else if(this.busMaterial.type===3) {
                this.materialLibrary([], 1, 3).then(val => {
                    this.busMaterial.videoResource = val[0].resource
                }).catch(err => {
                    this.busMaterial.videoResource = ''
                })
            }
        },
        chooseGoods() {
            if(this.busMaterial.goodsOrpackage===1) {
                this.goodsChoose({count:1}, this.busMaterial.goodsChecked).then(val=>{
                    this.busMaterial.goodsChecked = []
                    this.busMaterial.goodsChecked.push({
                        content: val[0].name,
                        marketPrice: val[0].marketValue,
                        picUrl: val[0].image,
                        price: val[0].price,
                        goodsId: val[0].goodsId,
                        goodsType: 1,
                        packType:'',
                        fromType:1
                    })
                })
                // console.log(this.busMaterial.goodsChecked)
            } else if(this.busMaterial.goodsOrpackage===2) {
                this.packageChoose({count:1}, this.busMaterial.packageChecked).then(val=>{
                    this.busMaterial.packageChecked = []
                    this.busMaterial.packageChecked.push({
                        content: val[0].name,
                        marketPrice: val[0].marketValue,
                        picUrl: val[0].image,
                        price: val[0].price,
                        packageId: val[0].packageId,
                        goodsType: 2,
                        packType: val[0].type,
                        fromType:3
                    })
                })
                // console.log(this.busMaterial.packageChecked)
            }
        },
        save() {
            this.$refs.form.validate(valid => {
                if(valid) {
                    if(this.busMaterial.linkType === 3){
                        if(this.busMaterial.goodsOrpackage === 1) {
                            if(this.busMaterial.goodsChecked.length === 0) {
                                this.$message.error('请选择商品')
                                return false
                            }   
                        }else if(this.busMaterial.goodsOrpackage === 2) {
                            if(this.busMaterial.packageChecked.length === 0) {
                                this.$message.error('请选择套餐')
                                return false
                            } 
                        }
                    }
                    var busData ={
                        cover: this.busMaterial.cover,
                        type:this.busMaterial.type,
                        fakeShareNum: this.busMaterial.fakeShareNum,
                        sort:this.busMaterial.sort,
                        title:this.busMaterial.title,
                        content: this.busMaterial.content,
                        id: this.busMaterial.id,
                        groupId: this.busMaterial.groupValue[0],
                        tagId: this.busMaterial.groupValue.length > 1 ? this.busMaterial.groupValue[1] : '',
                        linkObject: '',
                        linkType: this.busMaterial.linkType,
                        resourceObjectList: []
                    }
                    if(this.busMaterial.type === 1) {
                        busData.resourceObjectList.push({resourceType:1, resourceUrl:this.busMaterial.resource, videoPicUrl: ''})
                    } else if(this.busMaterial.type === 2) {
                        console.log(this.busMaterial.resourceList)
                        this.busMaterial.resourceList.forEach(item=>{
                            busData.resourceObjectList.push({resourceType:1, resourceUrl:item, videoPicUrl:''})
                        })    
                    } else if(this.busMaterial.type === 3) {
                        busData.resourceObjectList.push({
                            resourceType:2,
                            resourceUrl:this.busMaterial.videoResource,
                            videoPicUrl:this.busMaterial.videoPicUrl
                        })
                    }
                    if(this.busMaterial.linkType === 1){
                        busData.linkObject = null
                    } else if(this.busMaterial.linkType === 2) {
                        busData.linkObject = this.busMaterial.linkUrl
                    } else if (this.busMaterial.linkType === 3) {
                        if(this.busMaterial.goodsOrpackage === 1) {
                            busData.linkObject = {
                                content: this.busMaterial.goodsChecked[0].content,
                                picUrl:this.busMaterial.goodsChecked[0].picUrl,
                                price:this.busMaterial.goodsChecked[0].price,
                                marketPrice: this.busMaterial.goodsChecked[0].marketPrice,
                                targetValue:this.busMaterial.goodsChecked[0].goodsId,
                                goodsType:1,
                                packType:'',
                                fromType:1
                            }
                        } else if(this.busMaterial.goodsOrpackage === 2) {
                            busData.linkObject = {
                                content: this.busMaterial.packageChecked[0].content,
                                picUrl:this.busMaterial.packageChecked[0].picUrl,
                                price:this.busMaterial.packageChecked[0].price,
                                marketPrice: this.busMaterial.packageChecked[0].marketPrice,
                                targetValue:this.busMaterial.packageChecked[0].packageId,
                                goodsType:2,
                                packType:this.busMaterial.packageChecked[0].packType,
                                fromType:3
                            }
                        }   
                    }
                    console.log(busData)
                    this.btnLoading = true
                    this.request({
                        url: '/bus-material/save',
                        method: 'post',
                        data: busData
                    }).then((res) => {
                        console.log(res)
                        if(res.code===200) {
                            this.$message.success(res.msg)
                            this.btnLoading=false
                            this.$router.push({ name: 'material' })
                        }
                    }).catch((err)=> {
                        this.btnLoading = false
                    })   
                }     
            })
        },
        uploadImg(event, item) {
            if(item.length > 8) {
                this.$message.error('上传超过9张图片')
                return false
            }
            const file = event.target.files[0]
            if(!file.type.match('image/')){
                 this.$message.error('请上传图片')
                return false
            }
            this.picFileUpload(file, (res) => {
                item.push(this.replaceImgUrl(res.filePath));
            }, {limitSize:5})
        },
        beforeUpload(file) {
            if(!file.type.match('image/')){
                 this.$message.error('请上传图片')
                return false
            }
            const isLt5M = file.size / 1024 / 1024 < 5
            if (!isLt5M) {
                this.$message.error('上传图片大小不能超过 5MB!')
            }
            return isLt5M
        },
        beforeUploadVideo(file) {
            // console.log(file.type)
            if(!(file.type.match('video/mp4') || file.type.match('video/quicktime'))){
                this.$message.error('请上传MP4、MOV格式视频')
                return false
            }
            const isLt50M = file.size / 1024 / 1024 < 50
            if (!isLt50M) {
                this.$message.error('上传视频大小不能超过 50MB!')
            }
            return isLt50M
        },
        async getTagGroup() {
            const response = await this.request({
                url: '/bus-group/list?channelId=1',
                method: 'get'
            }).catch((err)=> {
                this.$message.error(err.msg)
            }) 
            if(response.code===200){
                var childrens = []
                response.data.forEach(item => {
                    if(item.busTagList){
                        childrens = []
                        item.busTagList.forEach(item2 =>{ 
                            childrens.push({
                                value:item2.id,
                                label:item2.name
                            })
                        })
                    }else {
                        childrens = []
                    }
                    this.groupList.push({
                        value:item.id,
                        label:item.name,
                        children: childrens
                    })
                })
            }
        },
        async getSortLast() {
            const sort = await this.request({
                url: '/bus-material/sort-last',
                method: 'get'
            }).catch((err)=> {
                this.$message.error(err.msg)
            }) 
            if(sort.code===200){
               this.sortLast = sort.data
            }
        },
    }   
  }
</script>
<style lang="scss">
    @import "../../../styles/_mixin.scss";
    .block-header{
        color: #1ea0ff;
        font-size: 14px;
        padding: 12px 0;
        margin-bottom: 12px;
        background: #f7f7f7;
        &>div{
            padding: 0 12px;
            border-left: 2px solid #1ea0ff;
        }
    }
    .uploadLocal{
        position: absolute;
        bottom: -40px;
        font-size: 16px;
        color: #409EFF;
        left: 60px;
    }
    .coupon-edit .el-form .el-textarea .el-textarea__inner{
        height: auto;
    }
    .adviceTxt{
        color: #8c939d
    }
    .use-type-block{
        @include flex;
        margin-left: 24px;
    }
    .add-btn-block{
        margin:  0 0 12px 24px;
    }
     .section-content{
         .el-input-group__prepend{
             padding: 0 5px;
         }
        .line{
            text-align: center;
        }
        .el-input{
            width: 100%;
            max-width: 500px;
            min-width: 150px;
        }
        .el-icon-delete{
            color: red;
            font-size: 16px;
            margin: 0 12px;
            cursor: pointer;
        }
        .goods-item{
            padding: 12px 0;
            // border: 1px solid #efefef;
            border-radius: 6px;
            position: relative;

            .avatar-uploader .el-upload,
            .upload-img-list li,
            .upload-img-list .upload-btn{
                width: 120px;
                height: 120px;
                line-height: 118px;
            }
            .upload-img-list .img-preview .img-preview-mask .mask-btn {
                margin-top: 47px;
                line-height: 36px;
                text-align: center;
            }

            .present-item{
                padding: 6px;
                border: 1px solid #efefef;
                margin-bottom: 12px;
                position: relative;

                .el-icon-error{
                    color: red;
                    font-size: 18px;
                    cursor: pointer;
                    top: 12px;
                    right: 12px;
                    position: absolute;
                    z-index: 9;
                }

                &>.el-form-item {
                    margin-bottom: 22px;
                }
                .el-input,
                .el-select{
                    width: 100%;
                    max-width: 160px;
                }
            }
        }
        .add-btn-block{
            margin:  0 0 12px 24px;
        }
        .footer-block{
            text-align: center;
            margin-top: 24px;
        }
    }
</style>
